import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Input, TreeSelect, Modal, Spin, message } from 'antd';
import buildTree from '../../utils/productTypeTools';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};

@connect(({ productType, loading }) => ({
  productType,
  loading: loading.models.productType,
}))
@Form.create()
class OperateModal extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      metaData: {},
      saving: false,
      visible: false,
      mode: 'add',
    };
  }

  componentDidMount() {
    const { visible, mode, metaData } = this.props;
    this.setState({ visible });
    this.setState({ mode });
    this.setState({ metaData: metaData || {} });
  }

  componentWillReceiveProps(nextProps) {
    const { visible: visiblePre } = this.state;
    const { form, visible, mode, metaData } = nextProps;
    this.setState({ mode });
    this.setState({ metaData: metaData || {} });

    if (mode === 'add') {
      if (visiblePre === false && visible === true) {
        form.resetFields();
      }
    }
    if (mode === 'update') {
      if (visiblePre === false && visible === true) {
        form.resetFields();
      }
    }
    this.setState({ visible });
  }

  handleOk = e => {
    e.preventDefault();
    const { dispatch, form, afterOK, mode } = this.props;
    const { metaData } = this.state;

    form.validateFields((err, values) => {
      if (!err) {
        this.setState({ saving: true });
        const submitValue = values;

        let dispatchType = '';
        let canSubmit = false;

        if (mode === 'add') {
          dispatchType = 'productType/add';
          canSubmit = true;
        } else if (mode === 'update') {
          submitValue.productTypeId = metaData.productTypeId;
          dispatchType = 'productType/update';
          canSubmit = true;
        } else {
          message.error(`组件配置错误，未知的提交模式${mode}！`);
        }

        if (canSubmit) {
          dispatch({
            type: dispatchType,
            payload: submitValue,
          }).then(() => {
            const {
              productType: { data },
            } = this.props;
            const { status } = data;
            this.setState({ saving: false });
            if (status === 200) {
              this.setState({ visible: false });
              afterOK(data);
            }
          });
        }
      }
    });
  };

  handleCancel = e => {
    e.preventDefault();
    const { afterCancel } = this.props;
    this.setState({ visible: false });
    afterCancel();
  };

  renderByMode = mode => {
    const { form, treeData, canSelect, showRoot } = this.props;
    const { metaData } = this.state;
    const { getFieldDecorator } = form;

    let result = null;

    if (mode === 'add') {
      if (!canSelect) {
        result = (
          <Fragment>
            <FormItem {...formItemLayout} label="上级分类">
              {getFieldDecorator('parentTypeName', {
                rules: [{ required: true, message: '请选择上级分类!' }],
                initialValue: metaData.name || '根分类',
              })(<Input placeholder="请选择分类名称" disabled />)}
            </FormItem>
            <FormItem {...formItemLayout} style={{ marginBottom: '0px' }}>
              {getFieldDecorator('parentTypeId', {
                rules: [{ required: true }],
                initialValue: `${metaData.productTypeId}` || '0',
              })(<Input type="hidden" />)}
            </FormItem>
          </Fragment>
        );
      } else {
        const treeDataAll = buildTree(treeData, showRoot);

        result = (
          <FormItem {...formItemLayout} label="上级分类">
            {getFieldDecorator('parentTypeId', {
              rules: [{ required: true, message: '请选择上级分类!' }],
              initialValue: metaData ? '0' : `${metaData.productTypeId}` || '0',
            })(
              <TreeSelect
                showSearch
                dropdownStyle={{ maxHeight: 260, overflow: 'auto' }}
                treeData={treeDataAll}
                placeholder="请选择上级分类"
                searchPlaceholder="在这里输入文字可以搜索选项哦"
                treeDefaultExpandAll
                onChange={this.onChange}
              />
            )}
          </FormItem>
        );
      }
    }

    if (mode === 'update') {
      const treeDataAll = buildTree(treeData, showRoot, metaData);

      if (metaData.defaultSet === '1') {
        result = (
          <Fragment>
            <FormItem {...formItemLayout} label="上级分类">
              {getFieldDecorator('parentTypeName', {
                rules: [{ required: true, message: '请选择上级分类!' }],
                initialValue: '根分类',
              })(<Input placeholder="请选择分类名称" disabled />)}
            </FormItem>
            <FormItem {...formItemLayout} style={{ marginBottom: '0px' }}>
              {getFieldDecorator('parentTypeId', {
                rules: [{ required: true }],
                initialValue: '0',
              })(<Input type="hidden" />)}
            </FormItem>
          </Fragment>
        );
      } else {
        result = (
          <FormItem {...formItemLayout} label="上级分类">
            {getFieldDecorator('parentTypeId', {
              rules: [{ required: true, message: '请选择上级分类!' }],
              initialValue: `${metaData.parentTypeId}` || '0',
            })(
              <TreeSelect
                showSearch
                dropdownStyle={{ maxHeight: 260, overflow: 'auto' }}
                treeData={treeDataAll}
                placeholder="请选择上级分类"
                searchPlaceholder="在这里输入文字可以搜索选项哦"
                treeDefaultExpandAll
                onChange={this.onChange}
              />
            )}
          </FormItem>
        );
      }
    }

    return result;
  };

  render() {
    const { form } = this.props;
    const { visible, mode, metaData, saving } = this.state;
    const { getFieldDecorator } = form;

    return (
      <Modal
        title={mode === 'add' ? '新增分类' : '编辑分类'}
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
      >
        <Spin spinning={saving}>
          <Form>
            <FormItem
              {...formItemLayout}
              label="分类名称"
              hasFeedback
              help="请在此输入您的产品分类名称。"
            >
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入分类名称!' }],
                initialValue: mode === 'add' ? '' : metaData.name,
              })(<Input placeholder="请输入分类名称" />)}
            </FormItem>
            {this.renderByMode(mode)}
          </Form>
        </Spin>
      </Modal>
    );
  }
}

export default OperateModal;
